# _*_ coding: utf-8 _*_
__author__ = 'yinlei'
__date__ = '2018-05-18 8:23'

from flask import (
    Blueprint,
    render_template,
    views,
    request,
    session,
    url_for,
    abort,
    g)
# (li>a)*4

import config
from apps.front.forms import Signupform, SigninForm, AddPostForm,AddCommentForm
from apps.front.models import FrontUser
from apps.models import Banner, BoardModel, PostModel,CommentModel,HighlightPostModel
from exts import db
from utils import zlcache, restful, safeutils
from .decorators import login_required
from flask_paginate import Pagination, get_page_parameter
from sqlalchemy.sql import func

front_route = Blueprint('front', __name__)


@front_route.route('/')
def index():
    board_id = request.args.get('bd',type=int,default=None)
    banners = Banner.query.order_by(Banner.priority.desc()).limit(4)
    boards = BoardModel.query.filter_by().order_by(BoardModel.create_time.desc()).all()

    page = request.args.get(get_page_parameter(), type=int, default=1)
    sort = request.args.get('sort',type=int,default=1)
    start = (page - 1) * config.PER_PAGE
    end = start + config.PER_PAGE
    total =0
    if sort == 1:
        query_obj = PostModel.query.order_by(PostModel.create_time.desc())
    elif sort == 2:
        query_obj = db.session.query(PostModel).outerjoin(HighlightPostModel).order_by(HighlightPostModel.create_time.desc(),PostModel.create_time.desc())
    elif sort==3:
        query_obj = PostModel.query.order_by(PostModel.create_time.desc())
    elif sort==4:
        query_obj = db.session.query(PostModel).outerjoin(CommentModel).group_by(PostModel.id).order_by(func.count(CommentModel.id).desc(),PostModel.create_time.desc())

    if board_id:
        query_obj = query_obj.filter(PostModel.board_id==board_id)
        posts = query_obj.slice(start, end)
        total = query_obj.count()
    else:

        posts = query_obj.slice(start, end)
        total = query_obj.count()
    pagination = Pagination(bs_version=3,page=page, total=total,per_page=config.PER_PAGE)
    context = {'banners': banners, 'boards': boards, 'posts': posts, 'pagination': pagination,'current_board':board_id,'sort':sort,'board_id':board_id}
    return render_template('front/front_index.html', **context)

@front_route.route('/post_detail/<post_id>')
def post_detail(post_id):
    post = PostModel.query.filter_by(id=post_id).first()
    if not post:
        abort(404)
    return render_template('front/front_post_detail.html',post=post)


@front_route.route('/add_post', methods=['GET', 'POST'])
@login_required
def add_post():
    if request.method == 'GET':
        boards = BoardModel.query.all()
        return render_template('front/front_add_post.html ', boards=boards)
    elif request.method == 'POST':
        form = AddPostForm(request.form)
        if form.validate():
            title = form.title.data
            content = form.content.data
            board_id = form.board_id.data
            board = BoardModel.query.filter_by(id=board_id).first()
            if board:
                with db.auto_commit():
                    post_model = PostModel(title=title, content=content, board_id=board_id)
                    post_model.author = g.front_user
                    db.session.add(post_model)
                return restful.success(message='发布成功')

            else:
                return restful.params_error(message='板块不存在')


        else:
            return restful.params_error(form.get_error())
        pass



@front_route.route('/add_comment',methods=['POST'])
@login_required
def add_comment():
    form = AddCommentForm(request.form)
    if form.validate():
        content = form.content.data
        post_id = form.post_id.data
        post = PostModel.query.get(post_id)
        if post:
            with db.auto_commit():
                comment = CommentModel(content=content,post=post,author=g.front_user)
                db.session.add(comment)
            return restful.success(message='评论成功')
        else:
            return restful.params_error(message='帖子不存在')
    else:
        restful.params_error(message=form.get_error())
@front_route.route('/logout')
@login_required
def logout():
    session.pop(config.FRONT_USER_ID)
    return render_template('front/front_signin.html')
class SignupView(views.MethodView):
    def get(self):
        return_to = request.referrer
        if return_to and return_to != request.url and safeutils.is_safe_url(return_to):
            return render_template('front/front_signup.html', return_to=return_to)
        else:
            return render_template('front/front_signup.html')

    def post(self):
        form = Signupform(request.form)
        if form.validate():
            username = form.username.data
            password = form.password1.data
            telephone = form.telephone.data
            graph_captcha = form.graph_captcha.data
            zlcache.delete(telephone)
            zlcache.delete(graph_captcha)
            user = FrontUser.query.filter_by(mobile=telephone).first()
            if user:
                return restful.params_error('用户已经注册,请直接登录')
            with db.auto_commit():
                front_user = FrontUser(username=username, mobile=telephone, password=password)
                db.session.add(front_user)
            return restful.success(message='注册成功')
        else:
            return restful.params_error(form.get_error())



class SigninView(views.MethodView):
    def get(self):
        return_to = request.referrer
        if return_to and return_to != request.url and return_to != url_for('front.signup') and safeutils.is_safe_url(
                return_to):
            return render_template('front/front_signin.html', return_to=return_to)
        else:
            return render_template('front/front_signin.html')

    def post(self):
        form = SigninForm(request.form)
        if form.validate():
            telephone = form.telephone.data;
            password = form.password.data
            remember = form.remember.data
            user = FrontUser.query.filter_by(mobile=telephone).first()
            if user and user.check_password(password):
                session[config.FRONT_USER_ID] = user.id
                if remember:
                    session.permanent = True
                return restful.success('登录成功')
            else:
                return restful.server_error(message='手机号码或密码错误')
        else:
            return restful.params_error(message='参数错误')


front_route.add_url_rule(rule='/signup', view_func=SignupView.as_view('signup'), endpoint='signup')
front_route.add_url_rule(rule='/signin', view_func=SigninView.as_view('signin'), endpoint='signin')
